﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using DomainModel.ClassMaps;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace DomainModel
{
    public static class NHSessionProvider
    {
        private static object syncObj = new object();
        private static volatile ISession session;
        public static ISession Session
        {
            get
            {
                if (session == null)
                {
                    lock (syncObj)
                    {
                        if (session == null)
                        {
                            session = BuildSession();
                        }
                    }
                }
                return session;
            }
        }
        private static ISession BuildSession()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            ISessionFactory factory = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
                .Mappings(
                x =>
                {
                    x.FluentMappings.AddFromAssemblyOf<UserClassMap>();
                }
            ).BuildSessionFactory();
            return factory.OpenSession();
        }
    }
}
